package io.gitee.yxsnake.framework.web.filter;

import cn.hutool.core.util.IdUtil;
import io.gitee.yxsnake.framework.core.constant.TraceCons;
import io.gitee.yxsnake.framework.core.utils.ip.IpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.SneakyThrows;
import org.jboss.logging.MDC;
import org.springframework.http.HttpMethod;

import java.io.IOException;

/**
 * @author snake
 * @description
 * @since 2024/11/13 13:23
 */
public class TraceFilter implements Filter {
    @Override
    @SneakyThrows
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        String method = httpServletRequest.getMethod();
        // 放行跨域预请求
        if (HttpMethod.OPTIONS.name().equalsIgnoreCase(method)) {
            filterChain.doFilter(httpServletRequest,httpServletResponse);
        }
        //如果有上层调用就用上层的ID
        String traceId = httpServletRequest.getHeader(TraceCons.TRACE_ID);
        String clientIp = httpServletRequest.getHeader(TraceCons.CLIENT_IP);
        if (traceId == null) {
            traceId = IdUtil.getSnowflakeNextIdStr();
        }
        if (clientIp == null) {
            clientIp = IpUtil.getIpAddr(httpServletRequest);
        }
        MDC.put(TraceCons.TRACE_ID, traceId);
        MDC.put(TraceCons.CLIENT_IP, clientIp);

        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }

    @Override
    public void destroy() {
        MDC.clear();
    }
}
